﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.SessionState;
using System.Data;
using System.Text;

namespace RDIFramework.WebApp.Modules.hander
{
    using RDIFramework.BusinessEntity;
    using RDIFramework.Utilities;
    using RDIFramework.ServiceAdapter;
    using RDIFramework.WebCommon;

    /// <summary>
    /// OrganizeAdminHander 的摘要说明
    /// </summary>
    public class OrganizeAdminHander : IHttpHandler, IRequiresSessionState
    {
        private string action 
        { 
            get 
            { 
                return RDIFramework.WebCommon.PublicMethod.GetString(getObj("action")); 
            } 
        }

        private object getObj(string key) { return RDIFramework.WebCommon.StringHelper.GetRequestObject(key); }


        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";           

            switch (action)
            {
                case "AddOrganize":
                    this.AddOrganize(context);
                    break;
                case "EditOrganize":
                    EditOrganize(context);
                    break;
                case "DeleteOrganize":
                    DeleteOrganize(context);
                    break;
                case "treedata":
                    string ss = GetJsonData();
                    ss = ss.Replace("FullName", "text").Replace("Id","id");
                    context.Response.Write(ss);
                    break;
                case "GetOrganizeByCategory":
                    GetOrganizeByCategory(context);
                    break;
                default:                  
                    ss = GetJsonData();                    
                    context.Response.Write(ss);
                    break;
            }
        }

        private PiOrganizeEntity GetPageOrganizeEntity(PiOrganizeEntity entity)
        {
            entity.ParentId = PublicMethod.GetInt(getObj("vparentid"));
            entity.FullName = PublicMethod.GetString(getObj("FullName"));
            entity.ShortName = PublicMethod.GetString(getObj("ShortName"));
            entity.Code = PublicMethod.GetString(getObj("Code"));
            entity.Category = PublicMethod.GetString(getObj("vcategory"));
            entity.Manager = PublicMethod.GetString(getObj("vmanager"));
            entity.AssistantManager = PublicMethod.GetString(getObj("vassistantmanager"));
            entity.OuterPhone = PublicMethod.GetString(getObj("OuterPhone"));
            entity.InnerPhone = PublicMethod.GetString(getObj("InnerPhone"));
            entity.Fax = PublicMethod.GetString(getObj("Fax"));
            entity.Postalcode = PublicMethod.GetString(getObj("Postalcode"));
            entity.Web = PublicMethod.GetString(getObj("Web"));
            entity.Address = PublicMethod.GetString(getObj("Address"));          
            entity.Enabled = PublicMethod.GetString(getObj("Enabled")) == "on" ? 1 : 0;
            entity.IsInnerOrganize = PublicMethod.GetString(getObj("IsInnerOrganize")) == "on" ? 1 : 0;
            entity.Description = PublicMethod.GetString(getObj("Description"));
            return entity;
        }

        #region private void AddOrganize(HttpContext ctx) 增加组织机构
        /// <summary>
        /// 增加组织机构
        /// </summary>
        /// <param name="ctx"></param>
        private void AddOrganize(HttpContext ctx)
        {
            PiOrganizeEntity entity = new PiOrganizeEntity();
            UserInfo vUser = Utils.UserInfo;
            entity = this.GetPageOrganizeEntity(entity);
            entity.DeleteMark = 0;
            if (vUser != null)
            {
                entity.CreateBy = vUser.RealName;
                entity.CreateUserId = vUser.Id;
            }
            string statusCode = string.Empty;
            string statusMessage = string.Empty;
            try
            {
                RDIFrameworkService.Instance.OrganizeService.Add(vUser, entity, out statusCode, out statusMessage);

                if (statusCode == StatusCode.OKAdd.ToString())
                {
                    ctx.Response.Write(new JsonMessage { Success = true, Data = "1", Message = statusMessage }.ToString());
                }
                else
                {
                    ctx.Response.Write(new JsonMessage { Success = false, Data = "0", Message = statusMessage }.ToString());
                }
            }
            catch (Exception ex)
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = "0", Message = statusMessage + ex.Message }.ToString());
            }
        }
        #endregion

        #region private void EditOrganize(HttpContext ctx) 修改组织机构
        /// <summary>
        /// 修改组织机构
        /// </summary>
        /// <param name="ctx"></param>
        private void EditOrganize(HttpContext ctx)
        {
            UserInfo vUser = Utils.UserInfo;
            string vId = PublicMethod.GetString(getObj("KeyId"));
            PiOrganizeEntity entity = RDIFrameworkService.Instance.OrganizeService.GetEntity(vUser, vId);
            entity = this.GetPageOrganizeEntity(entity);
            if (vUser != null)
            {
                entity.ModifiedBy = vUser.RealName;
                entity.ModifyUserId = vUser.Id;
            }
            
            string statusMessage = string.Empty;
            int returnValue = 0;
            try
            {
                returnValue = RDIFrameworkService.Instance.OrganizeService.Update(vUser, entity, out statusMessage);

                if (returnValue > 0)
                {
                    ctx.Response.Write(new JsonMessage { Success = true, Data = "1", Message = statusMessage }.ToString());
                }
                else
                {
                    ctx.Response.Write(new JsonMessage { Success = false, Data = "0", Message = statusMessage }.ToString());
                }
            }
            catch (Exception ex)
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = "0", Message = statusMessage + ex.Message }.ToString());
            }
        }
        #endregion

        #region private void DeleteOrganize(HttpContext ctx) 删除组织机构
        /// <summary>
        /// 删除组织机构
        /// </summary>
        /// <param name="ctx"></param>
        private void DeleteOrganize(HttpContext ctx)
        {
            string vId = PublicMethod.GetString(getObj("KeyId"));
            
            try
            {
                int returnValue = RDIFrameworkService.Instance.OrganizeService.SetDeleted(Utils.UserInfo, new string[] { vId });

                if (returnValue > 0)
                {     
                    ctx.Response.Write(new JsonMessage { Success = true, Data = "1", Message = RDIFrameworkMessage.MSG0013 }.ToString());
                }
                else
                {
                    ctx.Response.Write(new JsonMessage { Success = false, Data = "0", Message = RDIFrameworkMessage.MSG3020 }.ToString());
                }
            }
            catch (Exception ex)
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = "0", Message = RDIFrameworkMessage.MSG3020 + ex.Message }.ToString());
            } 
        }
        #endregion 


        /// <summary>
        /// 通过组织机构分类代码（Company、Department、SubDepartment、Workgroup）得到组织机构列表
        /// </summary>
        /// <param name="ctx"></param>
        private void GetOrganizeByCategory(HttpContext ctx)
        {
            //var d = JSON.stringify($('body').data('depData'));
            //d = '[{"id":0,"text":"请选择组织机构"},' + d.substr(1);

            //Company、Department、SubDepartment、Workgroup
            string returnJson = "[]";
            string[] names = { PiOrganizeTable.FieldCategory, PiOrganizeTable.FieldEnabled, PiOrganizeTable.FieldDeleteMark };
            string OrganizeCategory = PublicMethod.GetString(getObj("OrganizeCategory"));
            string[] values = { OrganizeCategory, "1", "0" };
            DataTable dtOrganize = RDIFrameworkService.Instance.OrganizeService.GetDTByValues(Utils.UserInfo, names, values);

            if (dtOrganize != null && dtOrganize.Rows.Count > 0)
            {
                returnJson = RDIFramework.WebCommon.JSONhelper.ToJson(dtOrganize);
                returnJson = @"[{""Id"":0,""FullName"":""请选择""}," + returnJson.Substring(1);
            }    

            ctx.Response.Write(returnJson);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string GetJsonData()
        {
            List<PiOrganizeEntity> list = new List<PiOrganizeEntity>();
            
            foreach (DataRow drow in GetOrganizeScope(string.Empty, false).Rows)
            {
                list.Add(new PiOrganizeEntity(drow));
            }

            return "[" + GroupJSONdata(list, null) + "]";
        }

        private List<PiOrganizeEntity> GetGroups(List<PiOrganizeEntity> groups, int? parentid)
        {
            return groups.FindAll(delegate(PiOrganizeEntity gm) { return gm.ParentId == parentid; });
        }

        private string GroupJSONdata(List<PiOrganizeEntity> groups, int? parentId)
        {
            StringBuilder sb = new StringBuilder();
            List<PiOrganizeEntity> list = GetGroups(groups, parentId);
            string json = "";
            foreach (PiOrganizeEntity gm in list)
            {

                //json = JSONhelper.ToJson(gm);
                json = RDIFramework.Utilities.JsonHelper.ObjectToJSON(gm);               
                json = json.TrimEnd('}');
                sb.Append(json);
                sb.Append(",");
                sb.Append("\"children\":[");
                sb.Append(GroupJSONdata(groups, gm.Id.Value));
                sb.Append("]},");
            }

            return sb.ToString().TrimEnd(',');
        }

        /// <summary>
        /// 获取组织机构权限域数据
        /// </summary>
        private DataTable GetOrganizeScope(string permissionItemScopeCode, bool isInnerOrganize)
        {
            UserInfo user = Utils.UserInfo;
            // 获取部门数据，不启用权限域
            DataTable dataTable = new DataTable(PiOrganizeTable.TableName);
            if ((user.IsAdministrator) || (String.IsNullOrEmpty(permissionItemScopeCode) || (!SystemInfo.EnableUserAuthorizationScope)))
            {
                RDIFrameworkService RDIFrameworkService = new RDIFrameworkService();
                dataTable = RDIFrameworkService.Instance.OrganizeService.GetDT(user);
            }
            else
            {
                dataTable = RDIFrameworkService.Instance.PermissionService.GetOrganizeDTByPermissionScope(user, user.Id, permissionItemScopeCode);
            }

            if (isInnerOrganize)
            {
                BusinessLogic.SetFilter(dataTable, PiOrganizeTable.FieldIsInnerOrganize, "1");
            }
            dataTable.DefaultView.Sort = PiOrganizeTable.FieldSortCode;
            return dataTable;
        }
    }
}